/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * WWcontrolUI.java
 *
 * Created on Oct 10, 2011, 3:11:26 PM
 */
package wwcontroluiclient;

//import com.phidgets.*;
//import com.phidgets.event.*;
import java.io.*;
import java.net.Socket;
//import java.util.Date;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
//import java.util.Timer;
//import java.util.TimerTask;
import javax.swing.filechooser.*;
//import java.text.SimpleDateFormat;
//import WWControlServer;
/**
 *
 * @author Michael Ferry
 */
public class WWControlUIClient extends javax.swing.JFrame {
   
     
    
    //private InterfaceKitPhidget ikf_pHORP;
//    public static final int NumberOfInterfaceKits=4;
//    public static final int ifk_pHORP_serial=174418;
//    public static final int ifk_HeaterSensor_serial=106721;
//    public static final int ifk_HeaterRelay_serial=133211;
//    public static final int ifk_MotorRelay_serial=123785;
//    public static final int ifk_pHORP_index=0;
//    public static final int ifk_HeaterSensor=1;
//    public static final int ifk_HeaterRelay=2;
//    public static final int ifk_MotorRelay=3;
//    public static final double PhidgetsRawSensorDynRange=4096;
//    
    public static final int MIN_TO_MILLSEC = 60000;
//    public static final int ControlInterval = 1000;
//    
//    public static final int[] HeaterSensorMap = {0,1,2,3};
//    public static final int DCMotorDO=3;
//    
//    public static final String[] ifks_Name = new String[NumberOfInterfaceKits];
//    
//    private InterfaceKitPhidget[] ifks = new InterfaceKitPhidget[NumberOfInterfaceKits];
    //Determines the default state for the Ratiometric state of each interface kit;
//    public static final boolean DefaultRatiometric_pHORP = false;
//    public static final boolean DefaultRatiometric_HeaterSensor = true;
//    
    private int DataCollectionIntervalMilliSeconds;
    private double DataCollectionIntervalMinutes;
    private WWControlClientCommThread CommChannel = null;
    
    private long MotorRunDurationMilli;
    private long MotorRunPeriodMilli;
    private static final long EmptyLong = 0;
    //private Socket WWControlServerSocket = null;
    //private PrintWriter out;
    //private BufferedReader in;
//    
//    private JFileChooser fc;
//    private Timer DataTimer = null;
//    private DataCollectionTask dTask = null;
//    
//    private Timer HeaterTimer = null;
//    private HeaterControlTask hTask = null;
//    private double TempSetPoint;
//    private double TempSetRange;
//    
//    private Timer MotorTimer = null;
////    private MotorControlTask mTask = null;
//    
//    //Minutes that the motor is running during a cycle
//    private double MotorRunDuration=15;
//    //Total cycle time in minutes
//    private double MotorPeriod=60;
//    private double MotorDutyCycle;
    
    
    //This is a variable which maps Heater Sensor Inputs on the Heater Sensor ifk to their
    //Corresponding relay outputs on the Heater Relay ifk
    
    
    //private String dataOutDir;
     
    //private String pHORPDataOutFile;
    //private String fSep = System.getProperty("file.separator");
    

    /** Creates new form WWcontrolUI */
    public WWControlUIClient() {

        
        initComponents();
        //SetupInterfaceKits();
        
        //jLabel1.setText(Phidget.getLibraryVersion());
        jCheckBox1.setEnabled(false);
        jCheckBox2.setEnabled(false);
        jCheckBox3.setEnabled(false);
        jCheckBox4.setEnabled(false);
        
        //Setup initial Motor control paramters
        //jTextField2.setText(Double.toString(MotorRunDuration));
        //jTextField3.setText(Double.toString(MotorPeriod));
        ComputeMotorRunParameters();
        //make sure the motor is turned off when the program begins
//        try{
//            //if(ifks[ifk_MotorRelay].isAttached()){
//                //ifks[ifk_MotorRelay].setOutputState(DCMotorDO, false);
//            }
//            
//        }catch(PhidgetException ex){
//            System.out.println(ex);
//        }
              
//        ikf_pHORP.open(ikf_pHORP_serial);
//        System.out.println("waiting for InterfaceKit attachment...");      
//        ikf_pHORP.waitForAttachment();
//        System.out.println(ikf_pHORP.getDeviceName());
//        
        //System.out.println(Phidget.getLibraryVersion());
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();
        jCheckBox3 = new javax.swing.JCheckBox();
        jCheckBox4 = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jTextField2 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jButton9 = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jButton11 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Exit Program");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Phigets Library version:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Phidgets attachments"));

        jCheckBox1.setText("pHandORPBoardAttached");

        jCheckBox2.setText("HeaterSensorBoardAttached");

        jCheckBox3.setText("HeaterRelayAttached");
        jCheckBox3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox3ActionPerformed(evt);
            }
        });

        jCheckBox4.setText("MotorRelayAttached");
        jCheckBox4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCheckBox1)
                    .addComponent(jCheckBox4)
                    .addComponent(jCheckBox2)
                    .addComponent(jCheckBox3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox4)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Digestor Heater Control"));

        jLabel3.setText("Digestor set temp (C):");

        jLabel4.setText("Digestor temp range (C):");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Temperature", null, null, null, null},
                {"Heater", null, null, null, null}
            },
            new String [] {
                "", "Digestor 1", "Digestor 2", "Digestor 3", "Digestor 4"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton7.setText("Start Heater Control");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jButton8.setText("Stop Heater Control");
        jButton8.setEnabled(false);
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jTextField4.setText("34.5");
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });

        jTextField5.setText("0.5");
        jTextField5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addComponent(jButton7)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jButton8))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(53, 53, 53))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton7)
                    .addComponent(jButton8))
                .addContainerGap(36, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Data Collection"));

        jLabel2.setText("Data collection interval (min)");

        jTextField1.setText("1");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jLabel5.setText("Output Path");

        jButton2.setText("Acquire Data");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton6.setText("End Data Acquisiton");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
                        .addGap(103, 103, 103))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(103, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton6)
                        .addContainerGap(55, Short.MAX_VALUE))))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton6))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Motor control"));

        jTextField2.setText("15");
        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jLabel6.setText("Motor runs for:");

        jLabel7.setText("Motor duty cycle:  %");

        jTextField3.setText("60");
        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jButton3.setText("Start Computer Control");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Motor ON");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Motor OFF");
        jButton5.setEnabled(false);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel8.setText("Motor is currently: OFF");

        jLabel9.setText("Motor will next turn on: ");

        jLabel10.setText("Motor was last off: ");

        jLabel11.setText("Motor control: manual");

        jLabel12.setText("(min) every:");

        jLabel13.setText("(min)");

        jButton9.setText("End Computer Control");
        jButton9.setEnabled(false);
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel9)
                            .addComponent(jLabel10)))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel11))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel7)
                                    .addGroup(jPanel4Layout.createSequentialGroup()
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE))))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jButton3)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel13))
                            .addComponent(jButton9))))
                .addGap(88, 88, 88))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton5)
                .addContainerGap(210, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton10.setText("Connect to server");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });

        jButton11.setText("Disconnect from server");
        jButton11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton11ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(362, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 271, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(460, 460, 460))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton10)
                    .addComponent(jButton11))
                .addContainerGap(118, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        CleanUp();
        System.out.print("closing...");
        dispose();
        System.exit(0);
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
        //System.out.println(jTextField1.getText());
        DataCollectionIntervalMinutes=Double.parseDouble(jTextField1.getText());
        DataCollectionIntervalMilliSeconds=(int)DataCollectionIntervalMinutes*MIN_TO_MILLSEC;
        
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jCheckBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox3ActionPerformed

    private void jCheckBox4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox4ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox4ActionPerformed
    //Begins data collection using text file output
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        //start data collection
        if(CommChannel != null){
            DataCollectionIntervalMinutes = Double.parseDouble(jTextField1.getText());
            DataCollectionIntervalMilliSeconds = (int) (DataCollectionIntervalMinutes * MIN_TO_MILLSEC);

            CommChannel.SetDataCollectionStateClient(true, DataCollectionIntervalMilliSeconds);
        }
 
    }//GEN-LAST:event_jButton2ActionPerformed
    //Stops data collection
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed

        //end data collection
        if(CommChannel != null){          
            CommChannel.SetDataCollectionStateClient(false, EmptyLong);
        }
    }//GEN-LAST:event_jButton6ActionPerformed
    public void SetDataCollectionUIState(boolean state){
        jButton2.setEnabled(!state);
            jTextField1.setEnabled(!state);
            jButton6.setEnabled(state);
//        if (state) {
//            jButton2.setEnabled(false);
//            jTextField1.setEnabled(false);
//            jButton6.setEnabled(true);
//        } else {
//            jButton2.setEnabled(true);
//            jTextField1.setEnabled(true);
//            jButton6.setEnabled(false);
//        }
    }
    
    public void SetIfkUIState(int ifk_number, boolean Attached){
        if(ifk_number == 0) jCheckBox1.setSelected(Attached);
        if(ifk_number == 1) jCheckBox2.setSelected(Attached);
        if(ifk_number == 2) jCheckBox3.setSelected(Attached);
        if(ifk_number == 3) jCheckBox4.setSelected(Attached);
    }
    
    public void SetMotorControlUIState(boolean state){
            jButton3.setEnabled(!state);
            jTextField2.setEnabled(!state);
            jTextField3.setEnabled(!state);
            jButton9.setEnabled(state);
//        if (state) {
//            jButton3.setEnabled(false);
//            jTextField2.setEnabled(false);
//            jTextField3.setEnabled(false);
//            jButton9.setEnabled(true);
//            
//            
//        } else {
//            jButton2.setEnabled(true);
//            jTextField1.setEnabled(true);
//            jButton6.setEnabled(false);
//        }
    }
    //Starts Heater control
    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        // TODO add your handling code here:
//        if (HeaterTimer == null) {
//            System.out.println("Heater Control Started");           
//            TempSetPoint = Double.parseDouble(jTextField4.getText());
//            TempSetRange = Double.parseDouble(jTextField5.getText());
//            HeaterTimer = new Timer();
//            hTask = new HeaterControlTask(ifks[ifk_HeaterSensor], ifks[ifk_HeaterRelay], TempSetPoint, TempSetRange);
//            HeaterTimer.scheduleAtFixedRate(hTask, 0, ControlInterval);
//            jButton7.setEnabled(false);
//            jTextField4.setEnabled(false);
//            jTextField5.setEnabled(false);
//            jButton8.setEnabled(true);
//        } else {
//            System.out.println("Heater Control already running");
//        }

    }//GEN-LAST:event_jButton7ActionPerformed
    //Stops Heater control
    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        // TODO add your handling code here:
//        if (HeaterTimer != null) {
//            hTask.cancel();
//            HeaterTimer.cancel();
//            hTask = null;
//            HeaterTimer = null;
//            jButton7.setEnabled(true);
//            jTextField4.setEnabled(true);
//            jTextField5.setEnabled(true);
//            jButton8.setEnabled(false);
//            System.out.println("Heater Control Ended");
//        } else {
//            System.out.println("Heater Control not currently running");
//        }
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField4ActionPerformed

    private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField5ActionPerformed
//Computer control of motor operation
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        //Start the motor control task
        if(CommChannel != null){
            //CommChannel.SendMessage("c bmc " + MotorRunDurationMilli + " " + MotorRunPeriodMilli);
            CommChannel.SetMotorControlStateClient(true, MotorRunDurationMilli,MotorRunPeriodMilli);
        }
        
//        if (MotorTimer == null) {
//            Date StartTime = new Date();
//            Date EndTime = null;
//
//            MotorTimer = new Timer();
//            mTask = new MotorControlTask(ifks[ifk_MotorRelay], StartTime, EndTime,
//                    (long) (MotorRunDuration * MIN_TO_MILLSEC), (long) (MotorPeriod * MIN_TO_MILLSEC));
//            MotorTimer.scheduleAtFixedRate(mTask, 0, ControlInterval);
//
//            System.out.println("Computer control of DC motor started");
//            jButton3.setEnabled(false);
//            jTextField2.setEnabled(false);
//            jTextField3.setEnabled(false);
//            jButton9.setEnabled(true);
//        } else {
//            System.out.println("Computer control of DC motor already running");
//        }
    }//GEN-LAST:event_jButton3ActionPerformed

    //Ends computer control of the DC motor
    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        //ShutDownComputerControlOfMotor();
        if(CommChannel != null){
            CommChannel.SetMotorControlStateClient(false, EmptyLong, EmptyLong);
        }
    }//GEN-LAST:event_jButton9ActionPerformed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed

        ComputeMotorRunParameters();
    }//GEN-LAST:event_jTextField2ActionPerformed

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed

        ComputeMotorRunParameters();
    }//GEN-LAST:event_jTextField3ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        ShutDownComputerControlOfMotor();
//        try {
//            if (ifks[ifk_MotorRelay].isAttached()) {
//                ifks[ifk_MotorRelay].setOutputState(WWcontrolUI.DCMotorDO, false);
//            }
//        } catch (PhidgetException e) {
//            System.out.println(e);
//        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        ShutDownComputerControlOfMotor();
//        try {
//            if (ifks[ifk_MotorRelay].isAttached()) {
//                ifks[ifk_MotorRelay].setOutputState(WWcontrolUI.DCMotorDO, true);
//            }
//        } catch (PhidgetException e) {
//            System.out.println(e);
//        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
        SetupServerConnection();
    }//GEN-LAST:event_jButton10ActionPerformed

    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
        // TODO add your handling code here:
        if(CommChannel != null){
            CommChannel.Disconnect();
            CommChannel = null;
        }
    }//GEN-LAST:event_jButton11ActionPerformed
    
    private void SetupServerConnection(){
         CommChannel = new WWControlClientCommThread(this);
         CommChannel.start();
         //CommChannel.SendMessage("s gs");
    }

    
    private void ShutDownComputerControlOfMotor(){
//        if (MotorTimer != null) {
//            mTask.cancel();
//            MotorTimer.cancel();
//            mTask = null;
//            MotorTimer = null;
//            jButton3.setEnabled(true);
//            jTextField2.setEnabled(true);
//            jTextField3.setEnabled(true);
//            jButton9.setEnabled(false);
//            System.out.println("Computer control of DC motor ended");
//        } else {
//            //System.out.println("Computer not currently controlling motor");
//        }
    }
    private void ComputeMotorRunParameters(){
        double MotorRunDuration = Double.parseDouble(jTextField2.getText());
        double MotorRunPeriod = Double.parseDouble(jTextField3.getText());
        double MotorDutyCycle = (MotorRunDuration / MotorRunPeriod);
        //System.out.println(MotorDutyCycle);
        //Make sure the duty cycle is not greater than 100% 
        if(MotorDutyCycle > 1){
            MotorRunPeriod = MotorRunDuration;
            jTextField3.setText(jTextField2.getText());
            MotorDutyCycle = (MotorRunDuration / MotorRunPeriod);
        }
        jLabel7.setText("Motor duty cycle: "+ MotorDutyCycle*100 + "%");
        MotorRunDurationMilli = (long)MotorRunDuration*MIN_TO_MILLSEC;
        MotorRunPeriodMilli = (long)MotorRunPeriod*MIN_TO_MILLSEC;
    }
    private void CleanUp(){
        if(CommChannel != null){
            CommChannel.Disconnect();
            CommChannel = null;
        }
//        try {
            //unhook the event listeners
//            ifk.removeSensorChangeListener(sensor_listener);
//            ifk.removeOutputChangeListener(output_listener);
//            ifk.removeInputChangeListener(input_listener);
//            
//            ifk.removeErrorListener(error_listener);
//            ifk.removeDetachListener(detach_listener);
//            ifk.removeAttachListener(attach_listener);

            //close the phidgets and set all digital outputs to zero
            //Shut down all tasks if they are currently running
              //if(CommChannel != null) CommChannel.
//            if(DataTimer != null) DataTimer.cancel();
//            if(dTask != null) dTask.cancel();
//            if(HeaterTimer != null) HeaterTimer.cancel();
//            if(hTask != null) hTask.cancel();
//            if(MotorTimer != null) MotorTimer.cancel();
//            if(mTask != null) mTask.cancel();
//            
//            for (int i = 0;i < ifks.length; i++){
//                //Shuts off all Digital outputs for safety when the program exits
//                if(ifks[i].isAttached()){
//                    if(ifks[i].getOutputCount()> 0){
//                        for (int j = 0;j < ifks[i].getOutputCount(); j++){
//                            //System.out.println("Shutting down output: "+j);
//                            ifks[i].setOutputState(j, false);
//                        }
//                    }
//                }
//                ifks[i].close();
//                ifks[i] = null;
//            }
//            
//            //dispose();
//            //System.exit(0);
//        } catch (PhidgetException ex) {
//            JOptionPane.showMessageDialog(this, ex.getDescription(), "Phidget Error" + ex.getErrorNumber(), JOptionPane.ERROR_MESSAGE);
//            //dispose();
//            //System.exit(0);
//        }
    //}
    
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //System.out.println("test out");
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new WWControlUIClient().setVisible(true);         
            }
        });
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JCheckBox jCheckBox3;
    private javax.swing.JCheckBox jCheckBox4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration//GEN-END:variables
}
